<?php

namespace app\controller;

use app\BaseController;
use app\controller\model;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
use think\helper\Str;

class Finance extends BaseController
{
    protected $getpath = "";
    protected $gobaluser = "";
    protected $tables;

    public function __construct($check = true)
    {
        if ($check) {
            checkuser();
            $this->gobaluser = Session::get("uid");
        }
        $this->tables = new model\Tables();
    }

    /////ssssssssssssssssssssssssssssssssssssssssssssssssssss
    public function yeepayS()
    {
        return view("yeepayS");
    }

    public function yeepaySAdd()
    {
        $id = request()->param("id");
        $id < 1 ? $id = 0 : '';
        $taskModel = new model\Task();
        if ($id > 0) {
            $re = DB::name($this->tables->yeepayS)->where("id", $id)->find();
            if (!$re) echojson([], 1, 'ID错误');
        } else {
            $re = [];
        }
        return view("yeepaySAdd")->assign(['data' => $re]);
    }

    public function yeepaySSave()
    {
        $data = request()->param();
        unset($data['id']);
        $id = request()->param("id");
        $field = request()->param("field");
        foreach ($data as $k => $v) {
            if ($k == 'content') continue;
            if ($v == '') echojson([], 1, '所有必填');
        }
        if ($field) {
            $value = request()->param("value");
            if ($field == 'status') {
                DB::name($this->tables->yeepayS)->where("id", $id)->update(['status' => $value]);
                echojson();
            }
            echojson([], 1, '数据错误');
        }
        if ($id > 0) {
            $re = DB::name($this->tables->yeepayS)->where("id", $id)->find();
            if ($re) {
                DB::name($this->tables->yeepayS)->where("id", $id)->update($data);
                echojson([], 0, '更新成功');
            } else {
                echojson([], 1, 'ID错误');
            }
        } else {
            $data['addTime'] = nowTime();
            $re = DB::name($this->tables->yeepayS)->insert($data);
            if ($re) {
                echojson([], 0, '添加成功');
            } else {
                echojson([], 1, 'ID错误');
            }
        }
    }

    public function yeepaySList()
    {
        $where = '1=1';
        $status = request()->param("status");
        $title = request()->param("title");
        $status == -1 ? $where .= " and status=-1" : '';
        $status == 1 ? $where .= " and status=1" : '';
        $title != '' ? $where .= " and title like '%$title%'" : '';
        $res = getpagedata($this->tables->yeepayS, "", false, $where);
    }


    //////////////A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2A2
    public function getAmount()
    {
        //代扣 A2
        $id = request()->param("id");
        $amount = request()->param("amount");
        $yeepayA2 = DB::name($this->tables->yeepayA2)->where("id", $id)->find();
        if (!$yeepayA2) echojson([], 1, 'ID错误');
        if ($amount > $yeepayA2['amount']) echojson([], 1, '超过了余额');
        if ($amount <= 0) echojson([], 1, '金额错误');
        $payModel = new model\apis\service\YeepayModel($id);
        $orderNo = getOrderNo();
        $re = $payModel->getAmount($orderNo, $amount, $yeepayA2['shopNo']);
        if (!isset($re['state']) || $re['state'] != 'SUCCESS') echojson([], 1, $re['error']['message']);
        if (!isset($re['result']['code']) || $re['result']['code'] != 'UA00000') echojson([], 1, '提交失败');
        $re = $re['result'];
        //写入已申请代扣列表
        DB::name($this->tables->yeepayA2Amount)->insert(['a2ID' => $id, 'amount' => $amount, 'addTime' => nowTime(), 'admin' => $this->gobaluser, 'yeepayNo' => $re['uniqueOrderNo'], 'orderNo' => $re['orderId']]);
        echojson([], 0, '申请成功');
    }

    public function toCard()
    {
        $id = request()->param("id");
        $payModel = new model\Service($id);
        $data = DB::name($this->tables->yeepayA2)->where("id", $id)->find();
        $account = DB::name($this->tables->yeepayS)->where('status', 1)->column("id,shopNo,title");
        $re = $payModel->getPayMoney();
        if (isset($re['code']) && $re['code'] == 200 && isset($re['msg']) && $re['msg'] == 'SUCCESS') {
            $amount = $re['data']['fundAccountBalance'];
            $up = ['amount' => $amount];
            DB::name($this->tables->yeepayA2)->where("id", $id)->update($up);
            $data['amount'] = $amount;
        }
        return view("toCard", compact('data', 'account'));
    }

    public function yeepayA2()
    {
        return view("yeepayA2");
    }

    public function income()
    {
        $account = DB::name($this->tables->yeepayS)->where('status', 1)->column("shopNo,title");
        return view("income");
    }

    public function yeepayA2Amount()
    {
        $id = request()->param("id");
        $payModel = new model\Service($id);
        $yeepayA2 = DB::name($this->tables->yeepayA2)->where("id", $id)->find();
//        dd($yeepayA2);
        if (!$yeepayA2) echojson([], 1, 'ID错误');
        $re = $payModel->getPayMoney();
//        dd($re);
        if (isset($re['code']) && $re['code'] == 200 && isset($re['msg']) && $re['msg'] == 'SUCCESS') {
            $amount = $re['data']['fundAccountBalance'];
            $up = ['amount' => $amount];
            if ($yeepayA2['title'] == '' || $yeepayA2['title'] == null) $up['title'] = $re['data']['merchantName'];
            DB::name($this->tables->yeepayA2)->where("id", $id)->update($up);
            echojson([], 0, '余额：' . $amount);
        }
        echojson([], 1, '查询失败');
    }

    public function A2Add()
    {
        $id = request()->param("id");
        $id < 1 ? $id = 0 : '';
        $taskModel = new model\Task();
        if ($id > 0) {
            $re = DB::name($this->tables->yeepayA2)->where("id", $id)->find();
            if (!$re) echojson([], 1, 'ID错误');
        } else {
            $re = [];
        }
        return view("A2Add")->assign(['data' => $re]);
    }

    public function rechargeAccount()
    {
        $id = request()->param("id");
        $id < 1 ? $id = 0 : '';
        $data = DB::name($this->tables->yeepayA2Amount)->where("id", $id)->find();
        $account = DB::name($this->tables->yeepayS)->where('status', 1)->column("id,shopNo,title");
        return view("rechargeAccount")->assign(['data' => $data, 'account' => $account]);
    }

    //分账到户
    public function yeepayRecharge()
    {
        $param = request()->param();
        $yeepayA2 = DB::name($this->tables->yeepayA2)->where("id", $param['id'])->find();
        if (empty($yeepayA2)) echojson([], 1, 'ID错误');
        $payModel = new model\apis\service\YeepayModel($param['id']);
        $orderNo = getOrderNo();
        $re = $payModel->getAmount($orderNo, $param['amount'], $yeepayA2['shopNo']);
        if (!isset($re['state']) || $re['state'] != 'SUCCESS') echojson([], 1, $re['error']['message'] ?? "余额代扣失败");
        if (!isset($re['result']['code']) || $re['result']['code'] != 'UA00000') echojson([], 1, '提交失败');
        $re = $re['result'];
        //写入已申请代扣列表
        DB::name($this->tables->yeepayA2Amount)->insert(['a2ID' => $param['id'], 'amount' => $param['amount'], 'addTime' => nowTime(), 'admin' => $this->gobaluser, 'yeepayNo' => $re['uniqueOrderNo'], 'orderNo' => $re['orderId'], 'auditTime' => nowTime()]);
        //分账
        //获取分账账号
        $account = DB::name($this->tables->yeepayS)->where("id", $param['account'])->find();
        $divido_number = getOrderNo();
        $divido = (new model\apis\service\YeepayModel($param['id']))->divide($orderNo, $re['uniqueOrderNo'], $divido_number, $param['amount'], $account['shopNo']);
        if ($divido['state'] != 'SUCCESS' || $divido['result']['status'] != 'SUCCESS') echojson([], 1, "分账失败！");
        $divido = $divido['result'];
        DB::name($this->tables->yeepayA2Amount)->where(['orderNo' => $orderNo])->update([
            "status" => 2,
            "divide" => $divido_number,
            "divide_no" => $account['shopNo'] . $account['title'],
            "divide_time" => $divido['createDate']
        ]);
        //确认提现
        $pay_succ = (new model\apis\service\YeepayModel($param['id']))->getPayMoney($account['shopNo']);
        if ($pay_succ['state'] != 'SUCCESS' && $pay_succ['result']['status'] != 'SUCCESS') echojson([], 1, "提现失败！");
        $pay_succ = $pay_succ['result'];
        DB::name($this->tables->yeepayA2Amount)->where(['orderNo' => $orderNo])->update([
            "ref_sn" => $pay_succ['yeepayFlowNo'],
            "over_time" => nowTime(),
            'status' => 1
        ]);
        echojson();
    }

    //分账列表
    public function yeepayDivide()
    {
        $payModel = new model\apis\service\YeepayModel();
        $items = $payModel->getPayMoney("10091515881");
        echojson($items);
//        $id = request()->param("id");
//        $id < 1 ? $id = 0 : '';
//        $data = DB::name($this->tables->yeepayA2Amount)->where("id", $id)->find();
//        if (empty($data)) echojson([], 1, "订单查询失败");
    }

    //提现到账
    public function yeepayTotal()
    {

    }

    public function yeepayA2Save()
    {
        $data = request()->param();
        unset($data['id']);
        $id = request()->param("id");
        $field = request()->param("field");
        foreach ($data as $k => $v) {
            if ($k == 'content') continue;
            if ($v == '') echojson([], 1, '所有必填');
        }
        if ($field) {
            $value = request()->param("value");
            if ($field == 'status') {
                DB::name($this->tables->yeepayA2)->where("id", $id)->update(['status' => $value]);
                echojson();
            }
            echojson([], 1, '数据错误');
        }
        if ($id > 0) {
            $re = r_one($this->tables->yeepayA2, "id=$id");
            if ($re) {
                DB::name($this->tables->yeepayA2)->where("id", $id)->update($data);
                echojson([], 0, '更新成功');
            } else {
                echojson([], 1, 'ID错误');
            }
        } else {
            $data['addTime'] = nowTime();
            $re = DB::name($this->tables->yeepayA2)->insert($data);
            if ($re) {
                echojson([], 0, '添加成功');
            } else {
                echojson([], 1, 'ID错误');
            }
        }
    }

    public function yeepayA2List()
    {
        $where = '1=1';
        $status = request()->param("status");
        $title = request()->param("title");
        $status == -1 ? $where .= " and status=-1" : '';
        $status == 1 ? $where .= " and status=1" : '';
        $title != '' ? $where .= " and title like '%$title%'" : '';
        $res = getpagedata($this->tables->yeepayA2, "", false, $where);
    }

    public function yeepayIncome()
    {
        $res = getpagedata($this->tables->yeepayA2Amount, "", false, "1=1");
    }
}
